/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.devmng.web;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.devmng.entity.DeviceMain;
import com.thinkgem.jeesite.modules.devmng.entity.TaskDetail;
import com.thinkgem.jeesite.modules.devmng.entity.TaskMain;
import com.thinkgem.jeesite.modules.devmng.service.*;
import com.thinkgem.jeesite.modules.devmng.vo.GetTaskDetailRequest;
import com.thinkgem.jeesite.modules.devmng.vo.GetTaskDetailResponse;
import com.thinkgem.jeesite.modules.devmng.vo.TaskMainExecDetailRequest;
import com.thinkgem.jeesite.modules.devmng.vo.TaskMainExecDetailResponse;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 任务Controller
 *
 * @author panda
 * @version 2017-12-04
 */
@Controller
@RequestMapping(value = "${adminPath}/devmng/taskMain")
public class TaskMainController extends BaseController {

    @Autowired
    private TaskMainService taskMainService;

    @Autowired
    private DeviceMainService deviceMainService;

    @Autowired
    private TaskDetailService taskDetailService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private TaskExecRecordAttaService taskExecRecordAttaService;

    @Autowired
    private MultitaskingService multitaskingService;

    @ModelAttribute
    public TaskMain get(@RequestParam(required = false) String id) {
        TaskMain entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = taskMainService.get(id);
        }
        if (entity == null) {
            entity = new TaskMain();
        }
        return entity;
    }

    @RequiresPermissions("devmng:taskMain:view")
    @RequestMapping(value = {"list", ""})
    public String list(TaskMain taskMain, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<TaskMain> page = taskMainService.findPage(new Page<TaskMain>(request, response), taskMain);
        model.addAttribute("page", page);
        return "modules/devmng/taskMainList";
    }

    @RequiresPermissions("devmng:taskMain:view")
    @RequestMapping(value = "form")
    public String form(TaskMain taskMain, Model model) {
        model.addAttribute("taskMain", taskMain);
        List<DeviceMain> deviceMainList = deviceMainService.findList(new DeviceMain());
        DeviceMain parentDeviceMain = new DeviceMain();
        parentDeviceMain.setId("0");
        parentDeviceMain.setDeviceName("所有设备");
        deviceMainList.add(parentDeviceMain);
        model.addAttribute("deviceMainList", deviceMainList);
        return "modules/devmng/taskMainForm";
    }

    @RequiresPermissions("devmng:taskMain:view")
    @RequestMapping(value = "generate")
    public String generate(TaskMain taskMain, Model model) {
        model.addAttribute("taskMain", taskMain);
        if (taskMain != null && StringUtils.isNotBlank(taskMain.getId())) {
            TaskDetail taskDetail = new TaskDetail();
            taskDetail.setTaskMainId(taskMain.getId());
            List<TaskDetail> taskDetailList = taskDetailService.findList(taskDetail);
            model.addAttribute("taskDetailList", taskDetailList);
        }
        return "modules/devmng/taskMainGenerate";
    }

    @RequiresPermissions("devmng:taskMain:view")
    @RequestMapping(value = "plannedTaskGeneration")
    public String plannedTaskGeneration(TaskMain taskMain, Model model) {
        model.addAttribute("taskMain", taskMain);
        return "modules/devmng/plannedTaskGeneration";
    }

    @RequiresPermissions("devmng:taskMain:view")
    @RequestMapping(value = "multitasking")
    public String multitasking(TaskMain taskMain, Model model) {
        model.addAttribute("taskMain", taskMain);
        return "modules/devmng/multitasking";
    }

    @RequiresPermissions("devmng:taskMain:view")
    @RequestMapping(value = "detail")
    public String detail(TaskMain taskMain, Model model) {
        model.addAttribute("taskMain", taskMain);
        List<DeviceMain> deviceMainList = deviceMainService.findListByTaskMainId(taskMain.getId());
        model.addAttribute("deviceMainList", deviceMainList);
        return "modules/devmng/taskMainDetail";
    }

    @RequiresPermissions("devmng:taskMain:edit")
    @RequestMapping(value = "save")
    public String save(TaskMain taskMain, String deviceInfoJson, Model model, RedirectAttributes redirectAttributes, String flag) {
        if (!beanValidator(model, taskMain)) {
            return form(taskMain, model);
        }
        if ("Y".equals(flag)) {
            taskMainService.save(taskMain);
            addMessage(redirectAttributes, "保存任务成功");
            return "redirect:" + Global.getAdminPath() + "/devmng/taskMain/?repage";
        }
        taskMainService.save(taskMain, deviceInfoJson);
        addMessage(redirectAttributes, "保存任务成功");
        return "redirect:" + Global.getAdminPath() + "/devmng/taskMain/?repage";
    }

    @RequiresPermissions("devmng:taskMain:edit")
    @RequestMapping(value = "multitaskingSave")
    public String multitaskingSave(TaskMain taskMain, Model model, RedirectAttributes redirectAttributes) {
        multitaskingService.save(taskMain);
        addMessage(redirectAttributes, "保存任务成功");
        return "redirect:" + Global.getAdminPath() + "/devmng/taskMain/?repage";
    }

    @RequiresPermissions("devmng:taskMain:edit")
    @RequestMapping(value = "delete")
    public String delete(TaskMain taskMain, RedirectAttributes redirectAttributes) {
        taskMainService.delete(taskMain);
        addMessage(redirectAttributes, "删除任务成功");
        return "redirect:" + Global.getAdminPath() + "/devmng/taskMain/?repage";
    }

    @RequiresUser
    @RequestMapping(value = "listTaskMainExecDetail")
    public String listTaskMainExecDetail(TaskMain taskMain, HttpServletRequest request, HttpServletResponse response
            , Model model, RedirectAttributes redirectAttributes, String taskFlag) {
        taskMain.setTaskStatus("CLOSE");
        Page<TaskMain> page = taskMainService.findPage(new Page<TaskMain>(request, response), taskMain);
        model.addAttribute("page", page);
        return "modules/devmng/taskMainExecDetailList";
    }

    @RequiresUser
    @RequestMapping(value = "taskMainExecDetailCompletedList")
    public String taskMainExecDetailCompletedList(TaskMainExecDetailRequest taskMainExecDetialRequest, HttpServletRequest request, HttpServletResponse response
            , Model model, TaskMain taskMain, String flag, String taskMainId) {
        if (StringUtils.isEmpty(taskMainId)) {
            taskMainId = taskMain.getId();
        }
        Page<TaskMainExecDetailResponse> pageParam = new Page<>(request, response);
        pageParam.setPageSize(10000);
        Page<TaskMainExecDetailResponse> page = taskMainService.listTaskMainExecDetail(pageParam,
                taskMainExecDetialRequest, taskMainId);
        model.addAttribute("taskMainId", taskMainId);
        model.addAttribute("page", page);
        model.addAttribute("taskMainExecDetialRequest", taskMainExecDetialRequest);
        return "modules/devmng/taskMainExecDetailCompletedList";
    }

    @RequiresUser
    @RequestMapping(value = "taskMainExecDetailListByDeviceMain")
    public String taskMainExecDetailListByDeviceMain(TaskMainExecDetailRequest taskMainExecDetialRequest, HttpServletRequest request, HttpServletResponse response
            , Model model, TaskMain taskMain, String taskMainId) {
        Page<TaskMainExecDetailResponse> page = new Page<>();
        if (StringUtils.isEmpty(taskMainId)) {
            taskMainId = taskMain.getId();
        }
        if (taskMainExecDetialRequest.getDeviceMain() != null) {
            page = taskMainService.listTaskMainExecDetail(new Page<TaskMainExecDetailResponse>(request, response),
                    taskMainExecDetialRequest, taskMainId);
        }
        model.addAttribute("taskMainId", taskMainId);
        model.addAttribute("page", page);
        model.addAttribute("taskMainExecDetialRequest", taskMainExecDetialRequest);
        return "modules/devmng/taskMainExecDetailListByDeviceMain";
    }

    @ResponseBody
    @RequestMapping(value = "taskMainExecDetailListByDevchkItemId")
    public List<TaskMainExecDetailResponse> taskMainExecDetailListByDevchkItemId(@RequestBody TaskMainExecDetailRequest taskMainExecDetialRequest, HttpServletRequest request, HttpServletResponse response) {
        Page<TaskMainExecDetailResponse> innerPage = new Page<>(request, response);
        innerPage.setPageSize(10000);
        Page<TaskMainExecDetailResponse> page = taskMainService.listTaskMainExecDetail(innerPage,
                taskMainExecDetialRequest, null);
        return page.getList();
    }


    @RequiresUser
    @RequestMapping(value = "taskMainExecDetailListSingle")
    public String taskMainExecDetailListSingle(TaskMainExecDetailRequest taskMainExecDetialRequest, HttpServletRequest request, HttpServletResponse response
            , Model model, TaskMain taskMain, String flag, String taskMainId) {
        if (StringUtils.isEmpty(taskMainId)) {
            taskMainId = taskMain.getId();
        }
        if ("Y".equals(flag)) {
            taskMain = taskMainService.get(taskMainId);
        }
        if (taskMainExecDetialRequest.getSysOffice() != null && StringUtils.isNotEmpty(taskMainExecDetialRequest.getSysOffice().getId())) {
            Office sysOffice = officeService.get(taskMainExecDetialRequest.getSysOffice().getId());
            if (sysOffice != null) {
                taskMainExecDetialRequest.setSysOffice(sysOffice);
            }
        }
        if (taskMainExecDetialRequest.getTaskOperator() != null && StringUtils.isNotEmpty(taskMainExecDetialRequest.getTaskOperator().getId())) {
            User user = systemService.getUser(taskMainExecDetialRequest.getTaskOperator().getId());
            if (user != null) {
                taskMainExecDetialRequest.setTaskOperator(user);
            }
        }
        Page<TaskMainExecDetailResponse> page = taskMainService.listTaskMainExecDetail(new Page<TaskMainExecDetailResponse>(request, response),
                taskMainExecDetialRequest, taskMainId);
        model.addAttribute("taskMainId", taskMainId);
        model.addAttribute("flag", "Y");
        model.addAttribute("page", page);
        model.addAttribute("taskMainExecDetialRequest", taskMainExecDetialRequest);
        return "modules/devmng/taskMainExecDetailListSingle";
    }


    @RequiresUser
    @RequestMapping(value = "getTaskDetail")
    @ResponseBody
    public GetTaskDetailResponse getTaskDetail(@RequestBody GetTaskDetailRequest request) {
        return taskExecRecordAttaService.getTaskDetail(request.getTaskMainId(), request.getDeviceMainId(), request.getDevchkItemId());
    }

    @RequiresUser
    @RequestMapping(value = "exportData")
    public void exportData(String taskMainId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Page<TaskMainExecDetailResponse> page = taskMainService.listTaskMainExecDetail(new Page<TaskMainExecDetailResponse>(),
                new TaskMainExecDetailRequest(), taskMainId);

        TaskMain taskMain = taskMainService.get(taskMainId);
        List<String> headerList = Lists.newArrayList();
        headerList.add("任务标题");
        headerList.add("任务执行人");
        headerList.add("任务类型");
        headerList.add("任务状态");
        headerList.add("车站值班人员");
        headerList.add("跟班人员");
        headerList.add("网调室人员");
        headerList.add("实际结束时间");
        headerList.add("设备名称");
        headerList.add("检修周期");
        headerList.add("检修内容");
        headerList.add("检修标准");
        headerList.add("检修方法");
        headerList.add("是否正常");
        headerList.add("备注");
        headerList.add("测量值");

        List<TaskMainExecDetailResponse> busiDataList = page.getList();

        List<List<String>> dataList = Lists.newArrayList();
        for (int i = 0; i < busiDataList.size(); i++) {
            TaskMainExecDetailResponse res = busiDataList.get(i);
            List<String> dataRowList = Lists.newArrayList();
            dataRowList.add(res.getTaskTitle());
            dataRowList.add(res.getTaskOperator().getName());
            dataRowList.add(DictUtils.getDictLabel(res.getTaskType(), "DEVCHK_PERIOD", "未知"));
            dataRowList.add(DictUtils.getDictLabel(res.getTaskStatus(), "TASK_MAIN_STATUS", "未知"));
            dataRowList.add(res.getStationDutyPerson());
            dataRowList.add(res.getStationAttendant());
            dataRowList.add(res.getNetDispatcher());
            if (res.getCloseDate() != null) {
                dataRowList.add(DateUtils.formatDateTime(res.getCloseDate()));
            } else {
                dataRowList.add("无完成时间");
            }

            dataRowList.add(res.getDeviceName());
            dataRowList.add(DictUtils.getDictLabel(res.getCheckPeriod(), "DEVCHK_PERIOD", "未知"));
            dataRowList.add(res.getCheckContent());
            dataRowList.add(res.getCheckStd());
            dataRowList.add(res.getCheckMethod());
            dataRowList.add(res.getNormalDesc());
            dataRowList.add(res.getRemarks());
            dataRowList.add(res.getMeatureDesc());
            dataList.add(dataRowList);
        }

        ExportExcel ee = new ExportExcel(taskMain.getTaskTitle(), headerList);

        for (int i = 0; i < dataList.size(); i++) {
            Row row = ee.addRow();
            for (int j = 0; j < dataList.get(i).size(); j++) {
                if (j == 15) {
                    String val = dataList.get(i).get(j);
                    val = StringUtils.replace(val, "<div>", "");
                    val = StringUtils.replace(val, "</div>", "\r\n");
                    Cell cell = ee.addCell(row, j, val);
                    cell.setCellValue(new HSSFRichTextString(val));

                } else {
                    ee.addCell(row, j, dataList.get(i).get(j));
                }
            }
        }

        ee.write(response, taskMain.getTaskTitle() + ".xlsx");

        ee.dispose();

    }
}